package com.gy.controller.result;

import com.alibaba.excel.EasyExcel;
import com.gy.config.BaiduOcrConfig;
import com.gy.controller.assistant.utils.PdfExtractUtil;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.*;
import com.gy.query.PatentsQuery;
import com.gy.query.PersonalAwardQuery;
import com.gy.result.Result;
import com.gy.service.PersonalAwardService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.PersonalAwardVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/personal/award")
@Api(tags = "个人获奖接口")
@CrossOrigin
public class PersonalAwardController {
    @Autowired
    private PersonalAwardService personalAwardService;

    @Autowired
    private BaiduOcrConfig baiduOcrConfig;


    @Autowired
    private PdfExtractUtil pdfExtractUtil;

    /**
     * 根据openid分页查看某个人的个人获奖信息
     */
    @PostMapping("/get/personal/award")
    @ApiOperation("根据openid查看某个人的个人获奖信息")
    public Result<PageVO<PersonalAward>> getPapers(@RequestBody PersonalAwardQuery personalAwardQuery){
        return personalAwardService.getPersonalAward(personalAwardQuery);
    }

    /**
     * 根据id主键删除个人获奖
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据id主键删除个人获奖")
    public Result deleteById(@PathVariable Long id){
        return personalAwardService.removePersonalAward(id);
    }

    /**
     * 根据id主键查询个人获奖信息
     */
    @GetMapping("/getPersonalById/{id}")
    @ApiOperation("根据id主键查询个人获奖信息")
    public Result getPersonalById(@PathVariable Long id)
    {
        return Result.success(personalAwardService.getPersonalAwardById(id));
    }

    /**
     * 更改个人获奖
     */
    @PutMapping("/update")
    @ApiOperation("更改个人获奖信息")
    public Result update(@RequestBody PersonalAward personalAward){
        return personalAwardService.updatePersonalAward(personalAward);
    }

    /**
     * 新增个人获奖
     */
    @PostMapping("/save")
    @ApiOperation("新增个人获奖")
    public Result AddPapers(@RequestBody PersonalAward personalAward){
        return Result.success(personalAwardService.savePersonalAward(personalAward));
    }


    /**
     * 根据多个id查询个人获奖
     */
    @PostMapping("/getPersonalByIds")
    @ApiOperation("根据多个id查询个人获奖")
    public Result getPersonalByIds(@RequestBody Long[] ids){
        return personalAwardService.getPersonalAwardByIds(ids);
    }


    /**
     * excel批量导出
     */
    @PostMapping("/export")
    @ApiOperation("excel批量导出")
    public void exportPersonalAward(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_PersonalAward.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("PersonalAward")
                .doWrite(transformedData);
    }

    /**
     * 汇总表格中返回个人获奖信息
     */
    @GetMapping("/getPersonalAwardsBySummary")
    @ApiOperation("汇总表格中返回个人获奖信息")
    public Result<List<PersonalAwardVO>> getPersonalAwardsBySummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户登录信息异常");
        }

        // 查询并选择 PersonalAwardVO 中的字段
        List<PersonalAward> list = personalAwardService.lambdaQuery()
                .eq(PersonalAward::getUserId, userId)
                .select(
                        PersonalAward::getTitle,
                        PersonalAward::getAwardLevel,
                        PersonalAward::getLevel,
                        PersonalAward::getGrantingUnit,
                        PersonalAward::getAwardTime,
                        PersonalAward::getAuthorRank
                )
                .list();


        // 将查询结果转换为 PersonalAwardVO 列表
        List<PersonalAwardVO> voList = list.stream()
                .map(personalAward -> PersonalAwardVO.builder()
                        .title(personalAward.getTitle())
                        .awardLevel(personalAward.getAwardLevel())
                        .level(personalAward.getLevel())
                        .grantingUnit(personalAward.getGrantingUnit())
                        .awardTime(personalAward.getAwardTime())
                        .authorRank(personalAward.getAuthorRank())
                        .build())
                .collect(Collectors.toList());

        return Result.success(voList);
    }


    /**
     * 新增：个人获奖文件解析接口
     * 功能：接收PDF图片路径→OCR识别→AI解析→返回结构化数据（供前端填充表单）
     * @param request 含filePath（PDF转图片后的imageBasePath，如pdf-images/xxx-uuid/）
     * @return 解析后的StudentAward + 原始OCR文本
     */
    @PostMapping("/parse")
    public Result<Map<String, Object>> parsePersonalAward(@RequestBody Map<String, String> request) {
        try {
            String filePath = request.get("filePath");
            // 1. 校验参数
            if (filePath == null || filePath.trim().isEmpty()) {
                return Result.error("个人获奖证书图片路径不能为空");
            }

            // 2. 提取OCR文本（个人获奖证书通常1-2页，无需限制页数，用全部页数）
            String ocrText = pdfExtractUtil.extractPdfTextFromImages(filePath, baiduOcrConfig);
            if (ocrText == null || ocrText.trim().isEmpty()) {
                return Result.error("OCR识别失败，未提取到文本");
            }

            // 3. AI解析个人获奖字段（调用学生获奖专属AI方法）
            StudentAward studentAward = pdfExtractUtil.extractStudentAwardByAi(ocrText);

            // 4. 返回结果（前端用于填充表单）
            return Result.success(Map.of(
                    "personalAward", studentAward, // 解析后的个人获奖数据
                    "rawOcrText", ocrText           // 原始OCR文本（供调试）
            ));

        } catch (Exception e) {
            log.error("个人获奖证书解析失败", e);
            return Result.error("解析失败：" + e.getMessage());
        }
    }
}
